var App = (function () {
	"use strict";

	var	workouts = {
			startDate: new Date(),
			endDate: null,
			exercises: []
		},
		newExercise = function () {
			return {
				name: "",
				startDate: new Date(),
				endDate: undefined,
				duration: 0,
				restBefore: 0,
				restAfter: 0,
				reps: 0,
				weight: 0,
				reps2: 0,
				weight2: 0
			};
		},
		exToHtml = function (ex) {
			return "<li><a href='#'>" +
				"<span class='pre'>" + ex.restBefore + "</span>" +
				"<span class='exercise'>" + ex.name + "</span>" +
				"<span class='rw'>" + ex.reps + "x" + ex.weight + "kg" + "</span>" +
				"</a></li>";
		},
		nextId = 0,
		current = newExercise(),
		endExercise = function () {
			current.endDate = new Date();
			current.duration = current.startDate.getTime() - current.endDate.getTime();
			current = undefined;
		},
		startExercise = function () {
			current = newExercise();
			current.name = "--New Exercise--";
			current.restBefore = "0'00";
			current.id = nextId = nextId + 1;
			workouts.exercises.push(current);
			return current;
		},
		nextItem = function () {
			return (current === undefined) ? startExercise() : endExercise();
		};

	workouts.exercises.push(newExercise());

	return {
		next : nextItem,
		get: function (i) {
			return workouts.exercises[i];
		},
		toHtml: exToHtml
	};
}());


$(document).ready(function () {
	"use strict";
	
	function pad(x) {
		return ("0" + x).slice(-2);
	}
	
	var startDate, lastStop;
	startDate = lastStop = new Date();
	var timer = $.timer(function () {
		var cda = new Date(new Date().getTime() - startDate.getTime());
		$("#totalTi").text("" + pad(cda.getHours() - 1) + ":" +
				pad(cda.getMinutes()) + ":" + pad(cda.getSeconds()));
		
		cda = new Date(new Date().getTime() - lastStop.getTime());
		$("#elapsedTi").text("" + pad(cda.getMinutes()) + ":" + pad(cda.getSeconds()));
	});
	
	timer.set({ time: 1000, autostart: true });

	$("#cont").click(function (event) {
		event.preventDefault();
		var next = App.next();
		lastStop = new Date();
		if (next) {
			$(App.toHtml(next)).hide().prependTo($("#exostats")).slideDown("fast");
			$(this).text("Rest").addClass("rest").removeClass("workout");
		} else {
			$(this).text("Workout").removeClass("rest").addClass("workout");
		}
	});
});


